package club.xyes.zkh.ecommerce.web.backstage.controller;

import club.xyes.zkh.ecommerce.commons.entity.Shop;
import club.xyes.zkh.ecommerce.commons.exception.BadRequestException;
import club.xyes.zkh.ecommerce.commons.properties.WebsiteConfigurationProperties;
import club.xyes.zkh.ecommerce.commons.util.EntityImagePathUtils;
import club.xyes.zkh.ecommerce.commons.util.TextUtil;
import club.xyes.zkh.ecommerce.commons.vo.GeneralResult;
import club.xyes.zkh.ecommerce.commons.vo.LayUiDataGrid;
import club.xyes.zkh.ecommerce.service.ShopService;
import club.xyes.zkh.ecommerce.web.controller.BaseController;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;

/**
 * Create by 郭文梁 2019/4/16 0016 18:10
 * ShopController
 * 商铺相关数据访问控制器
 *
 * @author 郭文梁
 * @data 2019/4/16 0016
 */
@RequestMapping("/backstage/shop")
@RestController
@Api("商铺相关接口")
public class ShopController extends BaseController<Shop> {
    private final ShopService shopService;
    private final WebsiteConfigurationProperties websiteConfigurationProperties;

    @Autowired
    public ShopController(ShopService service,
                          WebsiteConfigurationProperties websiteConfigurationProperties) {
        super(service);
        this.shopService = service;
        this.websiteConfigurationProperties = websiteConfigurationProperties;
    }

    /**
     * 创建商铺
     *
     * @param param 商铺
     * @return GR
     */
    @ApiOperation("创建商铺")
    @PostMapping("/")
    public GeneralResult<Shop> create(@RequestBody Shop param) {
        Shop shop = checkCreateParamAndCopy(param);
        if (TextUtil.isTrimedEmpty(param.getPassword())) {
            throw new BadRequestException("密码不能为空");
        }
        shop.setPassword(param.getPassword());
        Shop existsShop = shopService.findByLoginName(shop.getLoginName());
        if (existsShop != null) {
            throw new BadRequestException("登录名已存在");
        }
        Shop res = shopService.create(shop);
        return GeneralResult.ok(res);
    }

    /**
     * 检查参数 并将需要的字段拷贝到新的对象中
     *
     * @param param 参数
     * @return 拷贝结果
     */
    private Shop checkCreateParamAndCopy(Shop param) {
        return checkCreateParamAndCopy(param, new Shop());
    }

    /**
     * 检查参数 并将需要的字段拷贝到新的对象中
     *
     * @param param 参数
     * @return 拷贝结果
     */
    private Shop checkCreateParamAndCopy(Shop param, Shop shop) {
        if (param == null) {
            throw new BadRequestException("未传参数");
        }
        if (TextUtil.isTrimedEmpty(param.getName())) {
            throw new BadRequestException("名称不能为空");
        }
        shop.setName(param.getName());
        if (TextUtil.isTrimedEmpty(param.getLoginName())) {
            throw new BadRequestException("账户名称不能为空");
        }
        shop.setLoginName(param.getLoginName());
        if (TextUtil.isTrimedEmpty(param.getAddress())) {
            throw new BadRequestException("地址");
        }
        shop.setAddress(param.getAddress());
        if (TextUtil.isTrimedEmpty(param.getDailyHours())) {
            throw new BadRequestException("营业时间不能为空");
        }
        shop.setDailyHours(param.getDailyHours());
        if (TextUtil.isTrimedEmpty(param.getMerchantNo())) {
            throw new BadRequestException("商户号不能为空");
        }
        shop.setMerchantNo(param.getMerchantNo());
        if (TextUtil.isTrimedEmpty(param.getTerminalId())) {
            throw new BadRequestException("终端号不能为空");
        }
        shop.setTerminalId(param.getTerminalId());
        if (TextUtil.isTrimedEmpty(param.getAccessToken())) {
            throw new BadRequestException("扫呗口令不能为空");
        }
        shop.setAccessToken(param.getAccessToken());
        if (TextUtil.isTrimedEmpty(param.getGeneralPayUrl())) {
            throw new BadRequestException("支付地址不能为空");
        }
        shop.setGeneralPayUrl(param.getGeneralPayUrl());
        return shop;
    }

    /**
     * 分页查询所有商铺
     *
     * @param page  页码
     * @param limit 每页大小
     * @return LayUi数据表格数据模型
     */
    @ApiOperation("分页查询商铺")
    @GetMapping("/list")
    public LayUiDataGrid<Shop> list(@RequestParam("page") int page,
                                    @RequestParam("limit") int limit) {
        PageInfo<Shop> pageInfo = shopService.list(page, limit);
        List<Shop> list = pageInfo.getList();
        String shopLogoPath = websiteConfigurationProperties.getShopLogoPath();
        String shopPromotionImagePath = websiteConfigurationProperties.getShopPromotionImagePath();
        String serverPrefix = websiteConfigurationProperties.getStaticServerPrefix();
        list = EntityImagePathUtils.prettyLogoPath(list, serverPrefix, shopLogoPath);
        list = EntityImagePathUtils.prettyShopPromotionImagePath(list, serverPrefix, shopPromotionImagePath);
        pageInfo.setList(list);
        return LayUiDataGrid.fromPageInfo(pageInfo);
    }

    /**
     * 更新商铺信息
     *
     * @param id    ID
     * @param param 参数
     * @return GR
     */
    @ApiOperation("更新商铺信息")
    @PostMapping("/{id}")
    public GeneralResult<Shop> update(@PathVariable("id") Integer id,
                                      @RequestBody Shop param) {
        if (shopService.existsByLoginName(param.getLoginName(), Collections.singletonList(id))) {
            throw new BadRequestException("登录名已存在");
        }
        Shop shop = shopService.getRequired(id);
        Shop target = checkCreateParamAndCopy(param, shop);
        Shop res = shopService.updateById(target);
        return GeneralResult.ok(res);
    }

    /**
     * 重置密码
     *
     * @param id       shopId
     * @param password password
     * @return GR
     */
    @ApiOperation("重置密码")
    @PostMapping("/{id}/reset-password")
    public GeneralResult<Shop> resetPassword(@PathVariable("id") Integer id,
                                             @RequestParam("password") String password) {
        Shop shop = shopService.getRequired(id);
        Shop res = shopService.resetPassword(shop, password);
        return GeneralResult.ok(res);
    }

    /**
     * 设置商家序列号
     *
     * @param shopId ShopId
     * @param sn     序列号
     * @return GR
     */
    @ApiOperation("设置商铺SN")
    @PostMapping("/{id}/set-sn")
    public GeneralResult<Shop> setSn(@PathVariable("id") Integer shopId,
                                     @RequestParam("sn") String sn) {
        Shop existsShop = shopService.findBySn(sn);
        if (existsShop != null) {
            throw new BadRequestException("SN已存在");
        }
        Shop shop = shopService.getRequired(shopId);
        shop.setSn(sn);
        Shop res = shopService.updateById(shop);
        return GeneralResult.ok(res);
    }
}
